#include <linux/stdlib.h>
#include <linux/string.h>

/**
 * kmemdup - duplicate region of memory
 *
 * @src: memory region to duplicate
 * @len: memory region length
 * @gfp: GFP mask to use
 *
 * Return: newly allocated copy of @src or %NULL in case of error,
 * result is physically contiguous. Use kfree() to free.
 */
void *kmemdup(const void *src, size_t len, gfp_t gfp)
{
    void *p;

    p = kmalloc(len, gfp);
    if (p)
        memcpy(p, src, len);

    return p;
}

char *kmemdup_nul(const char *s, size_t len, gfp_t gfp)
{
    char *buf;

    if (!s)
        return NULL;

    /* '+1' for the NUL terminator */
    buf = kmalloc(len + 1, gfp);
    if (!buf)
        return NULL;

    memcpy(buf, s, len);
    /* Ensure the buf is always NUL-terminated, regardless of @s. */
    buf[len] = '\0';

    return buf;
}
